package com.jielin.handling.service.room.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.entity.police.PoliceMan;
import com.jielin.handling.entity.room.EquipmentCameraInfoVo;
import com.jielin.handling.entity.room.RoomCameraInfoVo;
import com.jielin.handling.entity.room.RoomInfoVo;
import com.jielin.handling.entity.room.RoomInformation;
import com.jielin.handling.entity.room.RoomRecord;
import com.jielin.handling.entity.room.RoomReserveLog;
import com.jielin.handling.entity.tsuspect.TSuspec;
import com.jielin.handling.mapper.police.PoliceManMapper;
import com.jielin.handling.mapper.room.RoomInformationMapper;
import com.jielin.handling.mapper.room.RoomRecordMapper;
import com.jielin.handling.mapper.room.RoomReserveLogMapper;
import com.jielin.handling.mapper.tsuspect.TSuspecMapper;
import com.jielin.handling.service.room.RoomInformationService;
import com.jielin.handling.util.DateUtil;
import com.jielin.handling.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class RoomInformationServiceimpl implements RoomInformationService {
    @Autowired
    private RoomInformationMapper roomInformationMapper;
    @Autowired
    private RoomRecordMapper roomRecordMapper;
    @Autowired
    private RoomReserveLogMapper reserveLogMapper;
    @Autowired
    private TSuspecMapper suspecMapper;
    @Autowired
    private PoliceManMapper policeManMapper;

    @Override
    public List<RoomInformation> findAllRoomStatus(String organizationId, int pageNum, int pageSize) {
        Page<RoomInformation> startPage = PageHelper.startPage(pageNum, pageSize);// 使用分页插件方法
        roomInformationMapper.findAllRoomStatus(organizationId);
        List<RoomInformation> list = startPage.getResult();
        for (RoomInformation roomInformation : list) {
            PoliceMan pm = policeManMapper.findpolicmanById(roomInformation.getPoliceid());
            roomInformation.setPolicename(pm == null ? "" : pm.getName());
//			roomInformation.setCreateDate(DateUtil.getDateByBaseStr(roomInformation.getCreateDate().toString(), DateUtil.DATE_FORMAT_HOURS));
        }
        return list;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public String reserveRoom(String roomId, String policeId, String suspectId, String orgId, int method,
                              String startDate, String endDate) {
        String roomrecordId = "-1";
        Date tmpStartDate = null;
        Date tmpEndDate = null;
        Calendar nowTime = Calendar.getInstance();
        if (StringUtil.isEmpty(startDate) || StringUtil.isEmpty(endDate)) {
            tmpStartDate = nowTime.getTime();
            nowTime.add(Calendar.MINUTE, 15);
            tmpEndDate = nowTime.getTime();
        } else {
            tmpStartDate = DateUtil.strToDateLong(startDate);
            tmpEndDate = DateUtil.strToDateLong(endDate);
        }
        RoomReserveLog rrl = RoomReserveLog.builder().id(StringUtil.generatorUUID()).recordId("").roomId(roomId)
                .policeId(policeId).roomStatus(0).method(method).startDate(tmpStartDate)
                .endDate(tmpEndDate).build();
        List<String> policeIdList = roomInformationMapper.findUseRoomPoliceIdByOrgId(orgId);
        if (policeIdList.contains(policeId)) {// 已经预约房间
            rrl.setRoomStatus(1);
            reserveLogMapper.addRoomReserveLog(rrl);
            return "-2";
        }
        RoomInformation rInformation = roomInformationMapper.findRoomInfoById(roomId);
        if (rInformation.getOrderis() == 1) {
            log.info(rInformation.getRoomname() + "此房间已有人预约");
            rrl.setRoomStatus(1);
            reserveLogMapper.addRoomReserveLog(rrl);
            return roomrecordId;
        } else if (rInformation.getRoomstatus() == 1) {
            log.info(rInformation.getRoomname() + "此房间已有人");
            rrl.setRoomStatus(1);
            reserveLogMapper.addRoomReserveLog(rrl);
            return roomrecordId;
        } else {
            log.info("RoomInformationService事务start...");
            try {
                TSuspec t = new TSuspec();
                t.setId(suspectId);
                TSuspec suspectState = suspecMapper.selectStatue(suspectId);
                if (!"8".equals(suspectState.getSuspectState())) {
                    t.setSuspectState("5");
                } else {
                    t.setSuspectState(suspectState.getSuspectState());

                }
                //	t.setSuspectState("5");
                suspecMapper.updateState(t);// 修改人员状态为 分配审讯室
                roomInformationMapper.reserveRoom(roomId, policeId);// 修改房间状态为占用
                RoomRecord r = new RoomRecord();
                r.setId(StringUtil.generatorUUID());
                r.setRoomid(roomId);
                r.setPoliceid(policeId);
                r.setSuspectid(suspectId);
                roomRecordMapper.addRoomRecord(r);// 初始化房间使用记录
                roomrecordId = r.getId();
                rrl.setRecordId(roomrecordId);
                reserveLogMapper.addRoomReserveLog(rrl);
            } catch (Exception e) {
                log.info("RoomInformationService 事务回滚:{}", e);
                rrl.setRoomStatus(1);
                reserveLogMapper.addRoomReserveLog(rrl);
                // 抛出异常让其回滚
                throw new RuntimeException("事务回滚");
            }
        }
        return roomrecordId;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int cancelreserveRoom(String roomId, String roomrecordId, String policeId) {
        int i = -1;
        String usePoliceId = roomInformationMapper.findUseRoomPoliceIdById(roomId);
        if (StringUtil.isEmpty(policeId)) {
            return i;
        } else {
            if (!StringUtil.isEmpty(usePoliceId)) {
                if (!policeId.equals(usePoliceId)) {
                    log.info("不是相同的人不能取消预约");
                    return -2;
                }
            }
        }
        log.info("RoomInformationService事务start...");
        try {
            roomInformationMapper.cancelreserveRoom(roomId);// 更新预约房间状态为空闲
            roomRecordMapper.updateRoomRecord("", roomrecordId);// 保存更新预约房间结束时间
            i = 1;
        } catch (Exception e) {
            log.info("RoomInformationService 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return i;
    }

    @Override
    public int useStartReserveRoom(String roomid) {
        return roomInformationMapper.useStartRoom(roomid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int useEndReserveRoom(String roomid, String roomrecordid, String leaveallcase) {

        log.info("RoomInformationService事务start...");
        int i = -1;
        try {
            roomInformationMapper.useEndRoom(roomid);// 更新使用中房间状态为空闲
            roomRecordMapper.updateRoomRecord(leaveallcase, roomrecordid);// 保存更新房间使用结束时间
            i = 1;
        } catch (Exception e) {
            log.info("RoomInformationService 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return i;
    }

    @Override
    public List<RoomCameraInfoVo> findRoomCameraInfoByOrganizationId(String organizationId) {
        if (StringUtil.isEmpty(organizationId)) {
            return null;
        }
        List<RoomInfoVo> ri = roomInformationMapper.findRoomCameraInfoByOrganizationId(organizationId);
        ri.forEach(roomInfoVo -> {
            PoliceMan policeMan = roomInformationMapper.findPersonInfoById(roomInfoVo.getId());
            if (policeMan != null) {
                roomInfoVo.setPoliceCode(policeMan.getPoliceCode());
                roomInfoVo.setPoliceName(policeMan.getName());
            }
        });
        List<RoomCameraInfoVo> roomCameraList = new ArrayList<>();
        RoomCameraInfoVo rci = null;
        for (int i = 0; i < ri.size(); i++) {// sxt011,sxt012,sxt008,sxt010(查询到的房间所有摄像头编号需要分割)
            rci = new RoomCameraInfoVo();
            rci.setId(ri.get(i).getId());
            rci.setRoomName(ri.get(i).getRoomName());
            rci.setPoliceName(ri.get(i).getPoliceName());
            rci.setPoliceCode(ri.get(i).getPoliceCode());
            rci.setOrderIs(ri.get(i).getOrderIs());
            rci.setRoomStatus(ri.get(i).getRoomStatus());
            rci.setDate(ri.get(i).getDate());
            EquipmentCameraInfoVo eci = null;
            List<EquipmentCameraInfoVo> cameraS = null;
            if (!StringUtil.isEmpty(ri.get(i).getCameraCode())) {
                String[] rId = ri.get(i).getCameraId().split(",");
                String[] rCameraS = ri.get(i).getCameraCode().split(",");
                String[] rIpS = ri.get(i).getIp().split(",");
                String[] rPortS = ri.get(i).getPort().split(",");
                String[] rUserNameS = ri.get(i).getUserName().split(",");
                String[] rPassWordS = ri.get(i).getPassWord().split(",");
                String[] rShootDirectionS = ri.get(i).getShootDirection().split(",");
                String[] rStatusS = ri.get(i).getStatus().split(",");

                cameraS = new ArrayList<>();
                for (int j = 0; j < rCameraS.length; j++) {
                    eci = new EquipmentCameraInfoVo();
                    eci.setEquipmentId(rId[j]);
                    eci.setEquipmentCode(rCameraS[j]);
                    eci.setIp(rIpS[j]);
                    eci.setPort(rPortS[j]);
                    eci.setUserName(rUserNameS[j]);
                    eci.setPassWord(rPassWordS[j]);
                    eci.setShootDirection(rShootDirectionS[j]);
                    eci.setStatus(rStatusS[j]);
                    cameraS.add(eci);
                }
                rci.setCamera(cameraS);
            }
            roomCameraList.add(rci);
        }
        return roomCameraList;
    }

    @Override
    public RoomCameraInfoVo findRoomCameraInfoByRoomId(String roomId) {
        if (StringUtil.isEmpty(roomId)) {
            return null;
        }
        RoomInfoVo ri = roomInformationMapper.findRoomCameraInfoByRoomId(roomId);
        if (ri != null) {
            RoomCameraInfoVo rci = null;
            rci = new RoomCameraInfoVo();
            rci.setId(ri.getId());
            rci.setRoomName(ri.getRoomName());
            rci.setPoliceName(ri.getPoliceName());
            rci.setPoliceCode(ri.getPoliceCode());
            rci.setOrderIs(ri.getOrderIs());
            rci.setRoomStatus(ri.getRoomStatus());
            rci.setDate(ri.getDate());
            EquipmentCameraInfoVo eci = null;
            List<EquipmentCameraInfoVo> cameraS = null;
            if (!StringUtil.isEmpty(ri.getCameraCode())) {
                String[] rId = ri.getCameraId().split(",");
                String[] rCameraS = ri.getCameraCode().split(",");
                String[] rIpS = ri.getIp().split(",");
                String[] rPortS = ri.getPort().split(",");
                String[] rUserNameS = ri.getUserName().split(",");
                String[] rPassWordS = ri.getPassWord().split(",");
                String[] rShootDirectionS = ri.getShootDirection().split(",");
                String[] rStatusS = ri.getStatus().split(",");

                cameraS = new ArrayList<>();
                for (int j = 0; j < rCameraS.length; j++) {
                    eci = new EquipmentCameraInfoVo();
                    eci.setEquipmentId(rId[j]);
                    eci.setEquipmentCode(rCameraS[j]);
                    eci.setIp(rIpS[j]);
                    eci.setPort(rPortS[j]);
                    eci.setUserName(rUserNameS[j]);
                    eci.setPassWord(rPassWordS[j]);
                    eci.setShootDirection(rShootDirectionS[j]);
                    eci.setStatus(rStatusS[j]);
                    cameraS.add(eci);
                }
                rci.setCamera(cameraS);
            }
            return rci;
        }
        return null;
    }

    @Override
    public void resetRoomStatus() {
        roomInformationMapper.selectAllRoomStatus().forEach(roomInfo -> {
            long currentTime = System.currentTimeMillis();
            long diff = (currentTime - roomInfo.getModifyDate().getTime()) / 1000 / 60;
//            System.out.println(diff + "分钟");
            // 房间预约超过30分钟没使用与使用超过4小时的房间
            if ((1 == roomInfo.getOrderis() && 30 < diff)
                    || (1 == roomInfo.getRoomstatus() && 60 * 4 < diff)) {
                // 重置为空闲状态
                roomInformationMapper.useEndRoom(roomInfo.getId());
            }
        });
    }

}
